import { App, Form, ModalProps } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useMemo, useState } from 'react';

import sharelink from '@/api/services/sharelink';
import { Alert, CustomDatePicker, Input } from '@/components/eai-design';
import { SvgIcon } from '@/components/icon';
import Modals from '@/components/modals/Modals';
import { useRequest2 } from '@/hooks/use-request';
import { SelectedDataset } from '@/pages/components/select-dataset';
import SelectDataset from '@/pages/components/select-dataset/SelectDataset';
import { useParams } from '@/router/hooks/use-params';
import { Channel, ChannelBase, ChannelType } from '@/types/share-link';

interface FormValues extends Omit<ChannelBase, 'limit'> {
  datasets: SelectedDataset[];
  limit: Omit<Channel['limit'], 'expiredTime'> & {
    expiredTime?: dayjs.Dayjs;
    maxUsagePoints?: number;
  };
}

interface FeishuModalProps extends ModalProps {
  open: boolean;
  channel?: FormValues | undefined;
  onCancel: () => void;
  onRefresh?: () => void;
  onApiKeyCreated?: (apiKey: string) => void;
}

const NewApiKeyModal = ({
  open,
  channel,
  onCancel,
  onRefresh,
  onApiKeyCreated,
}: FeishuModalProps) => {
  const { message } = App.useApp();
  const { appId = '' } = useParams() as {
    appId: string;
  };
  const [errorMsg, setErrorMsg] = useState('');

  // 使用 useMemo 避免 defaultChannel 每次渲染都变化，修复 useEffect 依赖警告
  const defaultChannel = useMemo<FormValues>(
    () => ({
      name: '',
      appId,
      permissions: [],
      type: ChannelType.apikey,
      limit: {
        expiredTime: undefined,
        maxUsagePoints: -1,
      },
      datasets: [],
    }),
    [appId],
  );

  const [form] = Form.useForm<FormValues>();

  const { runAsync: handleSubmit, loading: submitLoading } = useRequest2(async () => {
    try {
      const values = await form.validateFields();

      const channelData = {
        ...values,
        id: channel?.id,
        appId,
        type: ChannelType.apikey,
        permissions: values.datasets.map((dataset) => ({
          resource_type: dataset.type,
          resource_name: dataset.title,
          resource_id: dataset.key,
          action: 'read',
        })),
        limit: {
          ...values.limit,
          maxUsagePoints: values.limit.maxUsagePoints ?? -1,
          expiredTime: values.limit.expiredTime
            ? values.limit.expiredTime.format('YYYY-MM-DD HH:mm:ss')
            : undefined,
        },
      };

      const res = channel
        ? await sharelink.updateChannel(channelData)
        : await sharelink.createChannel(channelData);
      setErrorMsg('');
      onRefresh && onRefresh();
      onCancel();
      message.success(channel ? '编辑成功' : '创建成功');
      !channel && onApiKeyCreated && onApiKeyCreated(res);
    } catch (error) {
      console.error('表单验证失败:', error);
      setErrorMsg(error.message);
    }
  });

  useEffect(() => {
    if (channel) {
      // 转换日期字段，避免 Ant Design Form 验证错误
      const channelWithConvertedDates = {
        ...channel,
        limit: {
          ...channel.limit,
          expiredTime: channel.limit.expiredTime ? dayjs(channel.limit.expiredTime) : undefined,
        },
      };
      form.setFieldsValue(channelWithConvertedDates);
    } else {
      form.setFieldsValue(defaultChannel);
    }
    setErrorMsg('');
  }, [channel, defaultChannel, form, open]);

  return (
    <Modals
      title={channel ? '编辑秘钥' : '新建秘钥'}
      destroyOnHidden
      open={open}
      onCancel={onCancel}
      onOk={handleSubmit}
      width={480}
      confirmLoading={submitLoading}
    >
      {errorMsg && (
        <div className="mb-2">
          <Alert
            type="error"
            message={
              <div className="flex items-center gap-2">
                <SvgIcon icon="warning" />
                <span>{errorMsg}</span>
              </div>
            }
          />
        </div>
      )}
      <Form form={form} layout="vertical">
        <Form.Item label="名称" name="name" rules={[{ required: true, message: '请输入名称' }]}>
          <Input placeholder="请输入名称" />
        </Form.Item>

        <Form.Item label="过期时间" name={['limit', 'expiredTime']}>
          <CustomDatePicker showTime placeholder="请选择过期时间" format="YYYY-MM-DD HH:mm:ss" />
        </Form.Item>

        <Form.Item label="选择知识库" name="datasets">
          <SelectDataset appId={appId} />
        </Form.Item>
      </Form>
    </Modals>
  );
};

export default NewApiKeyModal;
